
  joint.shapes.basic.ImageTwo = joint.shapes.basic.Generic.extend({
        markup: '<g class="rotatable"><g class="scalable"><image class="image1"/></g><image class="image2"/><text/></g>',
        defaults: _.defaultsDeep({
            type: "basic.Image",
            attrs: {
                text: {
                    "font-size": 14,
                    text: "",
                    "text-anchor": "middle",
                    "ref-x": .5,
                    "ref-dy": 20,
                    "y-alignment": "middle",
                    fill: "#000000",
                    "font-family": "Arial, helvetica, sans-serif"
                }
            }
        }, joint.shapes.basic.Generic.prototype.defaults)
    });

var initTaskProcess = function () {

    var tuid = parent.tuid;  //任务单元id
    var parentTuExcuteId = parent.parentTuExcuteId;     //parentTuExcuteId参数

    //得到任务流程记录初始化(timeline)
    var findTaskLog = function (callback) {
        $.ajax({
            type: 'GET',
            url: '/rest/tsLog/findTaskLog',
            data: {parentTuExcuteId: parentTuExcuteId, tuId: tuid, page: 1, limit: 5},
            dataType: 'JSON',
            success: function (result) {
                $('.form-timeline').removeClass("visibility_hide");
                console.log(result.data);

                if (result.data.length > 0) {

                    var dateArray = $.map(result.data, function (v, i) {
                        var timeLen = v.startTime.length;
                        var date = v.startTime.slice(0, 10);
                        var time = v.startTime.slice(timeLen - 8, timeLen);
                        return {
                            tuExcuteId: v.tuExcuteId,
                            isFinished: v.isFinished,
                            date: date,
                            time: time,
                            tuTime: v.startTime
                        }
                    });

                    console.log(dateArray);
                    var columns = {'list': dateArray};
                    $('#tBody3').html(template($('#tpl2').html(), columns));
                    
                    
                   callback&&callback(); //自动更新流程函数

                    //高度自适应
                    var timelineHeight = $('.form-timeline').outerHeight(true) + 'px';
                    $('.contentChained').css("height", "calc(100% - " + timelineHeight + ")");

                    var currentTuExcuteId = result.data[0].tuExcuteId;

                    getStatus(currentTuExcuteId,0);

                } else {
                    $('.form-timeline').html("<span class='label_on_max'>没有启动时间</span>");
                    var timeHeight = $('.form-timeline').outerHeight(true) + 'px';

                    $('.contentChained').css("height", "calc(100% - " + timeHeight + ")");

                    getTask();
                }
            },
            error: function () {
                layer.msg("请求时间数据失败")
            }
        });
    };
    //任务流程状态初始化
    var getStatus = function (tuExcuteId,statusCode) {
        $.ajax({
            type : 'GET',
            url : '/rest/tsLog/findStepExcuteLog',
            data : {tuExcuteId:tuExcuteId},
            dataType : 'JSON',
            success : function (result) {
                console.log(result);

                var tuStatusArray = $.map(result.data,function (v,i) {
                    return {isFinished:v.isFinished,taskObjectId:v.taskObjectId,stepTypeCode:v.stepTypeCode,isError:v.isError}
                });
                console.log(tuStatusArray);
                if(statusCode === 0){
                    getTask(tuStatusArray);
                }else {
                    updateStatus(tuStatusArray,statusCode);
                }

            },
            error : function (data) {
                console.log(data);
                layer.msg("执行状态请求失败")
            }
        });
    };
    //更新任务流程状态
    var updateStatus = function (tuStatusArray,refreshCode) {
        console.log(graph.getElements());
        $.each(graph.getElements(),function (i, v) {
            var that = v;
            // console.log( paper.findViewByModel(that));
            $.each(tuStatusArray,function (i, v) {
                if(that.attributes.attrs.taskObjectId ===  v.taskObjectId && (that.attributes.isFinished !== v.isFinished || that.attributes.isError !== v.isError)){
                	console.log("改变")
                    that.attributes.isFinished = v.isFinished;
                    that.attributes.isError = v.isError;

                    var img2 = "";
            
                    if(parseInt(v.isFinished) === 0){
                    	  img2 = "/assets/custom/draw/img/dispatch_run.svg";
                    }else {
                        if(parseInt(v.isError) === 0 || v.isError === null){
                        	img2 = "/assets/custom/draw/img/dispatch_finish.svg";
                        }else {
                        	img2 = "/assets/custom/draw/img/dispatch_error.svg";
                        }
                     
                    }
                    
                    
                    that.attributes.attrs[".image1"]['xlink:href'] = img2;
                 
                    var view =  paper.findViewByModel(that);
                    view.$el.find(".image2").attr("xlink:href",img2);

                }
            })
        });

       var startTime = $('.selected').attr("data-tuTime");
       var title = "";
       if(refreshCode === 1){
           title = "启动时间为："+startTime
           layer.msg(title,{
               time : 1500
           })
       }
    
      
    };
    //任务流程初始化
    var getTask = function (tuStatusArray) {
        $.ajax({
            url :'/rest/tuLayout/selectGraphStepsAndLinks',
            type : 'GET',
            dataType: 'JSON',
            data :{tuId : parent.tuid},
            success :function (result) {

                console.log(result);
                var arr = [];
                if(result.object.stepList.length > 0){

                    console.log(tuStatusArray);
                    var positionX = 600;	
                    $.each(result.object.stepList,function(i,v){
                        var that = v; 
                        $.each(tuStatusArray,function (i, v) {
                            if(that.taskObjectId ===  v.taskObjectId){
                                that.isFinished = v.isFinished;
                                that.isError = v.isError;
                            }
                        });

                        console.log(that);
                        
                        var img1="",img2="";
                

                        var tableObj = new joint.shapes.basic.ImageTwo({
                            position: { x: positionX+=100, y:600 },
                            size: { width: 40, height: 40 },
                            id : v.stepId,
                            isFinished :v.isFinished,
                            isError : v.isError,
                            attrs: {
                            	"vertexType" : v.stepTypeCode,
                                'taskObjectId':v.taskObjectId,
                                ".image1": { width: 40, height: 40},
                                ".image2": { width: 20, height: 20, "ref-y": -20, "ref-x": 40},
                                text: {"ref-y": -5,text:v.name}
                            },
                            description: 'image'

                        });	
                        

                        if (v.stepTypeCode === 'START'){
                        	
                        	img1 = "/assets/custom/draw/img/process_start.png";
                        }else if (v.stepTypeCode === 'DXFLOW'){
                        	img1 = "/assets/custom/draw/img/DXFLOW.png";
                        	
                        		
                        }else if(v.stepTypeCode ==='procedure'){
                        	img1 = "/assets/custom/draw/img/saveProcess.png";
                        	
                        }else {
                        	img1 = "/assets/custom/draw/img/TU.png";
                        	
                        }
                        
                        
                        if(v.isFinished){ //是否存在

                            if(parseInt(v.isFinished) === 0){ //正在运行
                            	img2 = "/assets/custom/draw/img/dispatch_run.svg";
                            }else {
                                if(parseInt(v.isError) === 0 || v.isError === null){ //运行完成
                                	img2 = "/assets/custom/draw/img/dispatch_finish.svg";
                                }else {							//运行错误
                                	img2 = "/assets/custom/draw/img/dispatch_error.svg";
                                }
                            }

                        }else {
                        	
                        	img2 = "";
                      
                        }
                        tableObj.attributes.attrs[".image1"]['xlink:href'] = img1;
                        tableObj.attributes.attrs[".image2"]['xlink:href'] = img2;
                        

                        arr.push(tableObj)
                    });

                    $.each(result.object.linkList,function (i, v) {
                        var linkObj = new joint.shapes.app.Link({
                            "type" : 'app.Link',
                            "z": 2,
                            id : v.linkId,
                            source : {id : v.fromStepId},
                            target: {id : v.endStepId},
                               connector: { name: 'rounded' },
                           // smooth: true,
                            attrs: {
                                '.connection': {
                                    stroke: '#20C1DD',
                                    'stroke-width': 1.5,
                                    pointerEvents: 'none',
                                },
                                '.marker-target': {
                                    fill: '#20C1DD',
                                    stroke: '#fff',
                                    d: 'M 10 0 L 0 5 L 10 10 z'
                                }
                            },
                        });
                        arr.push(linkObj)
                    });
                    graph.addCell(arr);

                    var graphLayout = new joint.layout.TreeLayout({
                        graph: graph,
                        parentGap: 100,
                        siblingGap: 100,
                        direction : 'R'
                    });
                    graphLayout.layout();
                    paperScroller.centerContent();

                }
            },
            error : function (result) {
                console.log(result)
            }
        });
    };
    //添加单项列表
    var addFirstList = function (options,callback) {
        var list = options.list;
        var evt = options.evt;
        var mountObj = options.mountObj;
        console.log(evt.clientX,evt.clientY);
        console.log(evt);

        var ul = $('.item_ul');
        if(ul.length >0) {
            ul.remove();
        }
        var fa_item_ul = $('<ul class="vakata-context jstree-contextmenu jstree-default-contextmenu item_ul"></ul>');
        $.each(list,function(i,v){
        	if(i === 0){
        		fa_item_ul.append('<li><a href="#"><i class="iconfont icon-mimaxianshi"></i>'+v+'</a></li>');
        	}
            
        });
        fa_item_ul.appendTo(mountObj);
        var context = $('.vakata-context');
        context.css({'display':'block','position':'absolute','z-index':'1000','background':'#fff','left':''+(evt.clientX)+'px','top':''+(evt.clientY-60)+'px'}).on("click","a",function () {
            context.remove();
            callback();
        });

    };

    //返回的应用对象
    var object = {};
    object.init = function (callback) {
        findTaskLog(callback);
    };
    object.getStatus = getStatus;
    object.addFirstList = addFirstList;
    return object;
}();

$(document).ready(function () {
    //页面初始化
    initTaskProcess.init(function(){
    	//自动刷新运行状态
    	var tuexcuteid = $(".selected").attr("data-tuexcuteid");
    	console.log(tuexcuteid)
		var timer = setInterval(function () {
    	    $.ajax({
	    	    url :'/rest/tsLog/findTsLog',
	            type : 'GET',
	            dataType: 'JSON',
	            data :{tuExcuteId:tuexcuteid},
	            success : function(result){
	            	console.log(result.object.isFinished)
	            	var isFinished = result.object.isFinished;
	            	if(parseInt(isFinished) === 1){
	            		clearInterval(timer);
	            	}else {
	            		initTaskProcess.getStatus(tuexcuteid, 2)
	            	}
	            }
    	    })
    	},5000)

    	   //点击切换时间
        $('.time-horizontal').on('click', 'a', function () {
        		
            if (!$(this).hasClass("selected")) {
            	clearInterval(timer);
                var tuexcuteid = $(this).attr("data-tuexcuteid");
                initTaskProcess.getStatus(tuexcuteid, 1);
                
                 timer = setInterval(function () {
            	    $.ajax({
        	    	    url :'/rest/tsLog/findTsLog',
        	            type : 'GET',
        	            dataType: 'JSON',
        	            data :{tuExcuteId:tuexcuteid},
        	            success : function(result){
        	            	console.log(result.object.isFinished)
        	            	var isFinished = result.object.isFinished;
        	            	if(parseInt(isFinished) === 1){
        	            		clearInterval(timer);
        	            	}else {
        	            		initTaskProcess.getStatus(tuexcuteid, 2)
        	            	}
        	            }
            	    })
            	},5000)
            }

            $('.time-horizontal .selected').removeClass('selected');
            $(this).addClass('selected');
        });
    	
    });
    

   
  //双击元素
    paper.on('cell:pointerdblclick',function(cellView){
        if(cellView.model.attributes.attrs.vertexType === "TU"){
        	openTu(cellView);
        }else if(cellView.model.attributes.attrs.vertexType === "DXFLOW"){
        	
        	openDXFLOW(cellView);
        }
    });

    //右键事件
    paper.on("cell:contextmenu",function (cellView,evt) {
        console.log(cellView.model);
        if(cellView.model.attributes.attrs.vertexType === "TU"){
            //  一级列表参数
            var options = {list:["打开子任务单元"],evt:evt,mountObj:$("#app")};
            initTaskProcess.addFirstList(options,function () {
            	openTu(cellView);
            })
        }else if(cellView.model.attributes.attrs.vertexType === "DXFLOW") {
        	 var options = {list:["查看启动日志"],evt:evt,mountObj:$("#app")};	
        	 
        	 initTaskProcess.addFirstList(options,function () {
              
                 //parent.tuid = cellView.model.attributes.attrs.taskObjectId; //改变tuid参数
        		 openDXFLOW(cellView);
                
             })
        }

    });

    //点击空白处移除ul
    paper.on('blank:pointerdown', function(evt, x, y) {
        var ul = $('.item_ul');
        if(ul.length > 0){
            ul.remove();
        }
    });
    
    //打开TU
    function openTu(cellView){
    	var timeLog = $('.selected');
    	var tutime = timeLog.attr("data-tuTime")?"("+timeLog.attr("data-tuTime")+")":"(无启动时间)";
        var name = cellView.model.attributes.attrs.text+ tutime;
        var url =  '/page/dispatch/monitoringEr';//'assets/custom/draw/monitoringEr.html';
        var this_id = timeLog.attr("data-tuexcuteid") + cellView.model.attributes.attrs.taskObjectId;

        parent.parentTuExcuteId = timeLog.attr("data-tuexcuteid");   //改变parentTuExcuteId参数
        parent.tuid = cellView.model.attributes.attrs.taskObjectId; //改变tuid参数

        parent.addTab(name,url,this_id); //请求addTab方法
   }
    
    //打开DXFLOW
    function openDXFLOW(cellView){
    	 var  tuExcuteId = $('.selected').attr("data-tuexcuteid");
		 var  taskObjectId = cellView.model.attributes.attrs.taskObjectId;
		 parent.layer.open({
			 type : 2,
        	 title:"启动日志",
        	 maxmin : true,
        	 area:["900px","500px"],
        	 content:['/page/dispatch/execLog?tuExcuteId='+tuExcuteId+'&taskObjectId='+taskObjectId],
        	 btn:["关闭"]
         })
    }

});